<route lang="json5" type="page">
{
  style: {
    navigationStyle: "custom",
    navigationBarTextStyle: "black",
  },
}
</route>
<template>
  <view :class="{ 'fixed-touch': showDetail }" :style="{ '--bot': bottom + 8 + 'px' }">
    <cu-navbar :title="reqParams.type ? '菜品评价' : '菜品详情'"></cu-navbar>
    <!-- 解决popup弹窗滚动效果穿透，导致下层页面滚动问题 -->
    <view class="overlayer" @touchmove.prevent v-show="showDetail"></view>
    <view class="wrap">
      <!-- 菜肴信息 -->
      <cu-card>
        <view class="dishItemBox">
          <view class="img">
            <uv-image
              :src="dishInfo.dishUrl"
              width="192rpx"
              height="192rpx"
              :lazy-load="true"
              :fade-show="true"
              :observeLazyLoad="true"
              mode="aspectFit"
              radius="15rpx"
            >
              <template v-slot:error>
                <view style="font-size: 24rpx">加载失败</view>
              </template>
            </uv-image>
          </view>
          <view class="content">
            <view style="width: 75%">
              <view class="title ellipsis">{{ dishInfo.dishName }}</view>
              <view class="flex">
                <view style="margin-right: 30.77rpx"
                  >关注 {{ dishInfo.allFollow || 0 }}</view
                >
                <view>被选 {{ dishInfo.allChoose || 0 }}</view>
              </view>
              <view class="flex">
                <view>评价</view>
                <view>
                  <uv-rate
                    :allowHalf="true"
                    :readonly="true"
                    active-color="#FAD20C"
                    inactive-color="#DCDEE0"
                    gutter="0"
                    size="16"
                    :value="dishInfo.dishStar / 2"
                  ></uv-rate>
                </view>
              </view>
              <view class="ellipsis-3">
                描述 ：{{ dishInfo.describes || "暂无描述" }}</view
              >
            </view>
            <view>
              <uv-icon
                @click="onFollow()"
                :name="dishInfo.attent ? 'guanzhu' : 'guanzhu-1'"
                custom-prefix="custom-icon"
                size="38rpx"
                :color="dishInfo.attent ? '#ff363f' : '#CCCCCC'"
              ></uv-icon>
            </view>
          </view>
        </view>
      </cu-card>

      <cu-card margin="15rpx 0" padding="31rpx 31rpx 0 31rpx">
        <p>三项指数说明</p>
        <view style="width: 100%; height: 450rpx; overflow: hidden">
          <cu-radarChart
            :radarData="chartsDataRadar"
            :canvasId="'id' + dishInfo.dishCode"
            :radarOpts="optsRadar"
          ></cu-radarChart>
        </view>
      </cu-card>

      <view>
        <view v-if="commentList.length">
          <view :style="{ marginBottom: 60 + bottom + 'px' }">
            <dishesComment
              v-for="(item, index) in commentList"
              :itemData="item"
              :itemIdx="index"
              :key="index"
              @changelike="changelike"
            ></dishesComment>

            <uv-load-more
              line
              :status="loadMore.status"
              :loading-text="loadMore.loadingText"
              :loadmore-text="loadMore.loadmoreText"
              :nomore-text="loadMore.nomoreText"
              @loadmore="loadHandler"
            />
          </view>
        </view>
        <cu-empty v-else text="暂无评价数据"></cu-empty>
      </view>
      <view class="bottom" v-if="reqParams.type">
        <view class="btnBox">
          <uv-button
            shape="circle"
            color="#00754A"
            :disabled="commentStatus != 0"
            @click="goComment"
          >
            <span style="font-size: 31rpx">
              {{
                commentStatus == 1
                  ? "就餐已结束"
                  : commentStatus == -1
                  ? "就餐未开始"
                  : "前往评价"
              }}
            </span>
          </uv-button>
        </view>
      </view>

      <CommentPop ref="popRef" :reqParams="reqParams"  @close="closeFn"></CommentPop>
    </view>
  </view>
</template>

<script lang="ts" setup>
import {
  getAddBudgetOrder,
  getSaveOneAttention,
  getDeleteOneAttention,
} from "@/service/business/orderingDishes/index";
import {
  reqDishInfo,
  requdgeDish,
  reqComplaiComment,
  reqLikeEvaluater,
  reqDeleteLikeEvaluater,
} from "@/service/business/goods";
import dishesComment from "@/pages/components/dishesComment.vue";
import CommentPop from "./components/commentPop.vue";
import { getCurrentInstance } from "vue";
import { useUserStore } from "@/store";
const userStore = useUserStore();

const bottom = ref(userStore.pinia_SafeVal.bottom);

const showDetail = ref(false);
const popRef = ref(null);
// 请求参数
const reqParams = ref({
  type:'',
  dishCode: "",
  recipedtlId: "",
  userId: userStore.userInfo.user.userId,
});
const goComment = () => {
  popRef.value.open(reqParams.value.recipedtlId);
  showDetail.value = true;
};

// 关闭弹窗刷新评价内容
const closeFn = () => {
  console.log("close");
  showDetail.value = false;
  pageInfo.value.current = 1;
  commentList.value = [];
  getComplainAdvice();
};

// 关注菜品
const onFollow = () => {
  // item.attent为0是未被关注，为1是被关注
  if (dishInfo.value.attent) {
    getDeleteOneAttentionApi();
  } else {
    getSaveOneAttentionApi();
  }
};

// 关注菜品
const getSaveOneAttentionApi = () => {
  return new Promise((resolve) => {
    getSaveOneAttention({
      userId: userStore.userInfo.user.userId,
      dishCode: dishInfo.value.dishCode,
    }).then((res) => {
      if (res.retCode === 2000) {
        getDishInfo();
        uni.showToast({
          title: "关注菜品成功",
          icon: "none",
        });
      }
    });
  });
};
// 取消关注菜品
const getDeleteOneAttentionApi = () => {
  return new Promise((resolve) => {
    getDeleteOneAttention({
      userId: userStore.userInfo.user.userId,
      dishCode: dishInfo.value.dishCode,
    }).then((res) => {
      if (res.retCode === 2000) {
        getDishInfo();
        uni.showToast({
          title: "取消关注菜品成功",
          icon: "none",
        });
      }
    });
  });
};

// 改变点赞状态
const changelike = (idx) => {
  uni.vibrateShort();
  let { attent, evaluateId } = commentList.value[idx];
  if (attent) {
    getDeleteLikeEvaluater(evaluateId).then((res) => {
      commentList.value[idx].attent = 0;
    });
  } else {
    getLikeEvaluater(evaluateId).then((res) => {
      commentList.value[idx].attent = 1;
    });
  }
};
const getDeleteLikeEvaluater = (evaluateId) => {
  return new Promise<void>((resolve, reject) => {
    reqDeleteLikeEvaluater({ userId: userStore.userInfo.user.userId, evaluateId }).then(
      (res) => {
        if (res.retCode == 2000) {
          resolve();
        }
      }
    );
  });
};
const getLikeEvaluater = (evaluateId) => {
  return new Promise<void>((resolve, reject) => {
    reqLikeEvaluater({ userId: userStore.userInfo.user.userId, evaluateId }).then(
      (res) => {
        if (res.retCode == 2000) {
          resolve();
        }
      }
    );
  });
};

// 雷达图数据
const chartsDataRadar = reactive({
  categories: ["外观指数", "食材指数", "口味指数"],

  series: [
    {
      name: "数值",
      data: [],
      color: "#00754A",
      // textOffset:300,
    },
  ],
});

const optsRadar = reactive({
  padding: [0, 0, 0, 0],
  legend: {
    show: false,
  },
  extra: {
    radar: {
      gridType: "radar",
      gridCount: 4,
      opacity: 0.2,
      max: 15,
      borderWidth: 1,
      axisLabel: true,
      radius: 200,
    },
  },
});
// 菜肴信息
const dishInfo = ref({});
const getDishInfo = () => {
  reqDishInfo({ ...reqParams.value }).then((res) => {
    if (res.retCode === 2000) {
      dishInfo.value = res.data;
      chartsDataRadar.series[0].data = [
        res.data.dishAppearance,
        res.data.dishMaterial,
        res.data.dishFlavor,
      ];
    }
  });
};
// 评价状态
const commentStatus = ref(0);
const getudgeDish = () => {
  requdgeDish({ recipedtlId: reqParams.value.recipedtlId }).then((res) => {
    if (res.retCode === 2000) {
      commentStatus.value = res.data;
    }
  });
};

// 评价列表
const commentList = ref([]);
const getComplainAdvice = () => {
  loadMore.value.status = "loading";
  const params = {
    ...reqParams.value,
    current: pageInfo.value.current,
    size: pageInfo.value.size,
    kitchenId: userStore.userInfo.user.kitchenId,
  };
  reqComplaiComment(params).then((res) => {
    if (res.retCode === 2000) {
      commentList.value.push(...res.data);
      pageInfo.value.total = res.total;
      if (pageInfo.value.current < Math.ceil(res.total / pageInfo.value.size)) {
        loadMore.value.status = "loadmore";
      } else {
        loadMore.value.status = "nomore";
      }
    }
  });
};

const onInit = () => {
  getDishInfo();
  getComplainAdvice();
  if (reqParams.value.type) getudgeDish();
};

// 加载状态数据
const loadMore = ref({
  status: "loading",
  loadingText: "努力加载中",
  loadmoreText: "上拉或点击加载更多",
  nomoreText: "到底啦",
});

// 分页信息
const pageInfo = ref({
  size: 10,
  current: 1,
  total: null,
});

// 手动加载更多
const loadHandler = () => {
  loadMoreFn();
};

// 触底加载更多
onReachBottom(() => {
  console.log(6661);
  loadMoreFn();
});

const loadMoreFn = () => {
  if (pageInfo.value.current >= Math.ceil(pageInfo.value.total / pageInfo.value.size)) {
    loadMore.value.status = "nomore";
    return false;
  }
  pageInfo.value.current++;
  getComplainAdvice();
};

// 周食谱进入为1（可以点评），全部菜品进入没有
const type = ref(1);
onLoad((options) => {
  // type.value = options.type ? 1 : 0;
  // reqParams.value.dishCode = options.code;
  // reqParams.value.recipedtlId = options.id;

  
  const instance = getCurrentInstance().proxy;
  const eventChannel = instance.getOpenerEventChannel();
  eventChannel.on("mealInfo", function (data) {
    reqParams.value = Object.assign(reqParams.value,data.data)
    onInit();
  });
});
</script>

<style lang="scss" scoped>
//

.wrap {
  padding: 24rpx;
}
.dishItemBox {
  box-sizing: border-box;
  display: flex;
  justify-content: space-between;
  width: 100%;
  height: 192.31rpx;
  padding-right: 30.77rpx;
  margin-bottom: 46.15rpx;
  font-family: PingFang SC, PingFang SC;
  font-size: 23rpx;
  font-weight: 400;
  line-height: 38rpx;
  color: #969799;
  .img {
    width: 192rpx;
    height: 192rpx;
    margin-right: 15.38rpx;
  }

  .content {
    flex: 1;
    display: flex;
    justify-content: space-between;
    .title {
      font-size: 31rpx;
      font-weight: 600;
      line-height: 46rpx;
      color: #111111;
    }

    .selectBox {
      margin-top: 23.08rpx;

      .select {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 115rpx;
        height: 46rpx;
        font-size: 23rpx;
        font-weight: 400;
        color: #ffffff;
        background: linear-gradient(90deg, #00754a 0%, #006241 100%);
        border-radius: 73rpx;
      }
      .select:active {
        opacity: 0.6;
      }
      .selectActive {
        color: #00754a;
        background: #d4e9e2;
      }
    }
    .guanzhu {
      // width: 50rpx;
    }
  }
}
.bottom {
  width: 100%;
  background: rgba(212, 233, 226, 0.6);
  border-radius: 23rpx 23rpx 0rpx 0rpx;
  position: fixed;
  bottom: 0;
  left: 0;
  .btnBox {
    width: 100%;
    background: #fff;
    padding: 15rpx 31rpx var(--bot) 31rpx;
    border-radius: 23rpx 23rpx 0rpx 0rpx;
    box-sizing: border-box;
  }
}

.fixed-touch {
  position: fixed;
}
.overlayer {
  position: fixed;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  z-index: 500;
  background-color: #000;
  opacity: 0.5;
}
</style>
